package yxy.game.pm2.active.module;

import org.joda.time.DateTime;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.*;
import yxy.cherry.data.string.GameString;
import yxy.game.pm2.active.ActiveUtil;
import yxy.game.pm2.active.module.actcontrol.activeControl;
import yxy.game.pm2.active.module.actdata.ActDataCenter;
import yxy.game.pm2.active.module.lockorder.LockOrderInfo;
import yxy.game.pm2.active.module.subordinateclass.ghost.GhostActive;
import yxy.game.pm2.active.module.subordinateclass.ghost.GhostGachaTask;
import yxy.game.pm2.active.module.subordinateclass.ghost.GhostShop;
import yxy.game.pm2.active.module.subordinateclass.ghost.GhostTask;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.Item;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.AreaModule;
import yxy.game.pm2.bean.module.PlayerModule;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.task.Task;
import yxy.game.pm2.bean.task.TaskType;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.mail.MailHandle;
import yxy.game.pm2.module.mail.MailTypeEnum;
import yxy.game.pm2.module.task.TaskHandle;
import yxy.game.pm2.module.tip.TipHandle;
import yxy.game.pm2.module.tip.TipType;

import java.util.*;

public class ActiveModule_神魔卡 extends PlayerModule {

    //bean -----------------------------------------------------------
    public static final int acttype = 18;

    private int day;            //第几天
    private DateTime update;    //刷新时间

    private int selectid;
    //	private HashMap<Integer, Currency> curmap = new HashMap<Integer, Currency>();	//心仪武将	//key:标记数 vaule:奖励
    private int cknum;            //抽卡次数

    private ArrayList<GhostShop> gss = new ArrayList<GhostShop>();    //神魔卡商城
    private HashMap<Integer, GhostGachaTask> ghostmap = new HashMap<Integer, GhostGachaTask>();    //抽武将任务
    private GhostActive ga;        //活跃任务

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    public DateTime getUpdate() {
        return update;
    }

    public void setUpdate(DateTime update) {
        this.update = update;
    }

    public int getSelectid() {
        return selectid;
    }

    public void setSelectid(int selectid) {
        this.selectid = selectid;
    }

    //	public HashMap<Integer, Currency> getCurmap() {
//		return curmap;
//	}
//	public void setCurmap(HashMap<Integer, Currency> curmap) {
//		this.curmap = curmap;
//	}
    public int getCknum() {
        return cknum;
    }

    public void setCknum(int cknum) {
        this.cknum = cknum;
    }

    public ArrayList<GhostShop> getGss() {
        return gss;
    }

    public void setGss(ArrayList<GhostShop> gss) {
        this.gss = gss;
    }

    public HashMap<Integer, GhostGachaTask> getGhostmap() {
        return ghostmap;
    }

    public void setGhostmap(HashMap<Integer, GhostGachaTask> ghostmap) {
        this.ghostmap = ghostmap;
    }

    public GhostActive getGa() {
        return ga;
    }

    public void setGa(GhostActive ga) {
        this.ga = ga;
    }

    //func ------------------------------------------------------------

//	public static final int canget = 1;
//	public static final int hadget = 2;
//	public static final int cannotget = 3;

    public static final int gachatype1 = 1;
    public static final int gachatype10 = 10;

    /**
     * 创建实例
     **/
    private static ActiveModule_神魔卡 create(String playerCode) {
//		PlayerBean pb = PlayerBean.get(playerCode);
//		ServerBean sb = ServerBean.get(pb.getServerId());
        AreaBean ab = AreaModule.area(playerCode);
        activeControl sai = activeControl.get(ab.getAreaId(), acttype);
        if (sai != null) {
            ActiveModule_神魔卡 am = new ActiveModule_神魔卡();
            am.setPlayerCode(playerCode);
            am.setDay(1);
            am.setTimeline(sai.getTimeline());
            am.setUpdate(DateTime.now());

//			//抽将
//			actghost ag = ActDataCenter.getData(101, actghost.class, playerCode);
//			ArrayList<Currency> curs = (ArrayList<Currency>) Currency.create(ag.getIdealrewardtype(), ag.getIdealid(), ag.getIdealrewardnum());
//			for(int i = 0; i < curs.size(); i++) {
//				Currency cur = curs.get(i);
//				am.getCurmap().put(i + 1, cur);
//			}

            //商城
            Map<String, actghostshop> agsmap = ActDataCenter.getAllData(actghostshop.class, playerCode);
            for (actghostshop data : agsmap.values()) {
                GhostShop gs = new GhostShop();
                gs.setId(data.getId());
                gs.setGoodsid(data.getChargeid());
                gs.setLimitnum(data.getLimit());
                am.getGss().add(gs);
            }

            //抽将任务
            Map<String, actghostreward> agrmap = DataCenter.getAllData(actghostreward.class);
            for (actghostreward data : agrmap.values()) {
                GhostGachaTask gt = new GhostGachaTask();
                gt.setId(data.getId());
                gt.setTaskid(data.getTaskid());

                task taskdata = DataCenter.getData(data.getTaskid(), task.class);
                if (taskdata == null) {
                    continue;
                }

                Task taskbean = Task.create(playerCode, taskdata);
                gt.setTaskcode(taskbean.getCode());
                am.getGhostmap().put(data.getId(), gt);
            }

            //活跃任务
            GhostActive ga = new GhostActive();
            Map<String, actghosttask> agtmap = DataCenter.getAllData(actghosttask.class);

            int activegroup = 1;
            ArrayList<Integer> activegroups = new ArrayList<Integer>();
            for (actghosttask data : agtmap.values()) {
                if (activegroups.contains(data.getGroup())) {
                    continue;
                }
                activegroups.add(data.getGroup());
            }

            if (!activegroups.contains(activegroup)) {
                Collections.sort(activegroups);
                if (activegroups.size() >= 1) {
                    activegroup = activegroups.get(0);
                }
            }
            ga.setActivegroup(activegroup);

            ga.setZhboxgetnum(0);

            for (actghosttask data : agtmap.values()) {

                if (activegroup != data.getGroup()) {
                    continue;
                }

                GhostTask gt = new GhostTask();
                gt.setId(data.getId());
                gt.setPosition(data.getPosition());
                gt.setTaskid(data.getTaskid());

                task taskdata = DataCenter.getData(data.getTaskid(), task.class);
                if (taskdata == null) {
                    continue;
                }

                Task taskbean = Task.create(playerCode, taskdata);
                if (taskbean == null) {
                    continue;
                }

                gt.setTaskcode(taskbean.getCode());

                ga.getActivemap().put(data.getId(), gt);
            }

            //组合任务

            am.setGa(ga);

            am.set();
            TaskHandle.handle(playerCode, TaskType.统计型_登录_次数, 1);
            return am;
        }

        return null;
    }

    //刷新 重新开启
    private void reset() {
        setDay(1);
        setUpdate(DateTime.now());

        //商城
        setGss(new ArrayList<GhostShop>());
        Map<String, actghostshop> agsmap = ActDataCenter.getAllData(actghostshop.class, getPlayerCode());
        for (actghostshop data : agsmap.values()) {
            GhostShop gs = new GhostShop();
            gs.setId(data.getId());
            gs.setGoodsid(data.getChargeid());
            gs.setLimitnum(data.getLimit());
            getGss().add(gs);
        }

        //抽将任务
        for (GhostGachaTask gt : getGhostmap().values()) {
            Task.remove(getPlayerCode(), gt.getTaskcode());
        }
        setGhostmap(new HashMap<Integer, GhostGachaTask>());
        Map<String, actghostreward> agrmap = DataCenter.getAllData(actghostreward.class);
        for (actghostreward data : agrmap.values()) {
            GhostGachaTask gt = new GhostGachaTask();
            gt.setId(data.getId());
            gt.setTaskid(data.getTaskid());

            task taskdata = DataCenter.getData(data.getTaskid(), task.class);
            if (taskdata == null) {
                continue;
            }

            Task taskbean = Task.create(getPlayerCode(), taskdata);
            gt.setTaskcode(taskbean.getCode());
            getGhostmap().put(data.getId(), gt);
        }

        //活跃任务
        for (GhostTask gt : getGa().getActivemap().values()) {
            Task.remove(getPlayerCode(), gt.getTaskcode());
        }
//		GhostActive ga = new GhostActive();
        Map<String, actghosttask> agtmap = DataCenter.getAllData(actghosttask.class);

        int activegroup = 1;
        ArrayList<Integer> activegroups = new ArrayList<Integer>();
        for (actghosttask data : agtmap.values()) {
            if (activegroups.contains(data.getGroup())) {
                continue;
            }
            activegroups.add(data.getGroup());
        }

        if (!activegroups.contains(activegroup)) {
            Collections.sort(activegroups);
            if (activegroups.size() >= 1) {
                activegroup = activegroups.get(0);
            }
        }
        getGa().setFinishpositions(new ArrayList<Integer>());
        getGa().setActivegroup(activegroup);
        getGa().setZhboxgetnum(0);

        for (GhostTask gt : getGa().getActivemap().values()) {
            Task.remove(getPlayerCode(), gt.getTaskcode());
        }
        getGa().setActivemap(new HashMap<Integer, GhostTask>());
        getGa().setFinishnumboxgetids(new ArrayList<Integer>());
        getGa().setFinishpositions(new ArrayList<Integer>());
        getGa().setZhgetids(new ArrayList<Integer>());

        for (actghosttask data : agtmap.values()) {
            if (activegroup != data.getGroup()) {
                continue;
            }

            GhostTask gt = new GhostTask();
            gt.setId(data.getId());
            gt.setPosition(data.getPosition());
            gt.setTaskid(data.getTaskid());

            task taskdata = DataCenter.getData(data.getTaskid(), task.class);
            if (taskdata == null) {
                continue;
            }

            Task taskbean = Task.create(getPlayerCode(), taskdata);
            if (taskbean == null) {
                continue;
            }

            gt.setTaskcode(taskbean.getCode());

            getGa().getActivemap().put(data.getId(), gt);
        }

        set();
        TaskHandle.handle(getPlayerCode(), TaskType.统计型_登录_次数, 1);
    }

    /**
     * 更新
     **/
    private void update() {
        PlayerBean pb = PlayerBean.get(getPlayerCode());
        ServerBean sb = ServerBean.get(pb.getServerId());
        activeControl sai = activeControl.get(String.valueOf(sb.getAreaId()), String.valueOf(acttype));
        if (sai == null) {
            return;
        }

        //根据开服时间计算是否达到活动开启的循环回合，动态修改活动的启始时间

        //关闭活动
        if (!sai.running()) {
            huishou();
        }

        if (!sai.running() && running()) {
            setTimeline(sai.getTimeline());
            set();
        }

        //开启活动
        if (sai.running() && !running()) {
            setTimeline(sai.getTimeline());
            reset();
        }

        //更新
        DateTime now = DateTime.now();
        int days = ActiveUtil.days(getUpdate(), now);
        if (days >= 1) {        //转天更新
            int newdays = getDay() + days;
            setDay(newdays);
            setUpdate(now);

            //活跃任务
            for (GhostTask gt : getGa().getActivemap().values()) {
                Task.remove(getPlayerCode(), gt.getTaskcode());
            }
            GhostActive ga = getGa();
            ga.setActivemap(new HashMap<Integer, GhostTask>());
            Map<String, actghosttask> agtmap = ActDataCenter.getAllData(actghosttask.class, getPlayerCode());

            int newactivegroup = ga.getActivegroup() + 1;
            ArrayList<Integer> activegroups = new ArrayList<Integer>();
            for (actghosttask data : agtmap.values()) {
                if (activegroups.contains(data.getGroup())) {
                    continue;
                }
                activegroups.add(data.getGroup());
            }

            if (!activegroups.contains(newactivegroup)) {
                Collections.sort(activegroups);
                if (activegroups.size() >= 1) {
                    newactivegroup = activegroups.get(0);
                }
            }
            ga.setActivegroup(newactivegroup);
//			ga.setFinishnumboxgetids(new ArrayList<Integer>());
            ga.setZhgetids(new ArrayList<Integer>());
            ga.setFinishpositions(new ArrayList<Integer>());

            for (actghosttask data : agtmap.values()) {
                if (newactivegroup != data.getGroup()) {
                    continue;
                }

                GhostTask gt = new GhostTask();
                gt.setId(data.getId());
                gt.setPosition(data.getPosition());
                gt.setTaskid(data.getTaskid());

                task taskdata = DataCenter.getData(data.getTaskid(), task.class);
                if (taskdata == null) {
                    continue;
                }

                Task taskbean = Task.create(getPlayerCode(), taskdata);
                if (taskbean == null) {
                    continue;
                }

                gt.setTaskcode(taskbean.getCode());
                ga.getActivemap().put(data.getId(), gt);
            }
            set();
            TaskHandle.handle(getPlayerCode(), TaskType.统计型_登录_次数, 1);
        }

        //更新 检查锁单
        boolean save = false;
        for (GhostShop gs : getGss()) {
            ArrayList<String> removemyorderids = new ArrayList<String>();
            DateTime nowtime = DateTime.now();
            for (String myorderid : gs.getLock().keySet()) {
                if (nowtime.getMillis() - gs.getLock().get(myorderid).getMillis() >= LockOrderInfo.lockTime()) {
                    removemyorderids.add(myorderid);
                    save = true;
                }
            }

            for (String myorderid : removemyorderids) {
                gs.getLock().remove(myorderid);
            }
        }

        if (save) {
            set();
        }
    }

    private void huishou() {
        try {
            //todo 活动关闭，清除背包的没消耗完的活动道具
            //如果背包存在就转成对应物品邮件发送
            Currency currency = Item.get(getPlayerCode(), CurrencyType.CT_物品, 1039);
            if (currency.getNumber() > 0) {
                item item_ = DataCenter.getData(1039, item.class);
                new CurrencyHandle().cost(getPlayerCode(), CCReason.神魔夺宝卷清空, currency);
                //邮件补偿
                List<Currency> list = new ArrayList<>();
                Currency reward = Currency.create(item_.getReclaimtype(), item_.getReclaimid(), currency.getNumber() * item_.getReclaimnum());
                list.add(reward);
                String title = GameString.活动结束自动回收_title().getText();
                String content = GameString.活动结束自动回收_msg("神魔降临", "" + currency.getNumber(), "" + item_.getName(), "" + currency.getNumber() * item_.getReclaimnum()).getText();
                new MailHandle().sendMail(getPlayerCode(), MailTypeEnum.Mail, title, content, CCReason.神魔夺宝卷清空, list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 能否购买
     *
     * @param goodsid
     * @return
     */
    public int canbuy(int goodsid) {
        for (GhostShop gs : getGss()) {
            if (gs.getGoodsid() == goodsid) {
                if (gs.getBuy().size() + gs.getLock().size() < gs.getLimitnum()) {
                    return DrawStatus.canget.getStatus();
                }
            }
        }

        return DrawStatus.cannotget.getStatus();
    }

    /**
     * 锁单
     *
     * @param goodsid
     * @param myorderid
     */
    public void lockorder(int goodsid, String myorderid) {
        for (GhostShop gs : getGss()) {
            if (gs.getGoodsid() == goodsid) {
                gs.getLock().put(myorderid, DateTime.now());
            }
        }
        set();
    }

    /**
     * 解锁单
     *
     * @param goodsid
     */
    public void unlockorder(int goodsid, String myorderid) {
        for (GhostShop gs : getGss()) {
            if (gs.getGoodsid() == goodsid) {
                gs.getLock().remove(myorderid);
            }
        }
        set();
    }

    /**
     * 处理购买
     *
     * @param goodsid
     * @param myorderid
     */
    public void handlebuy(int goodsid, String myorderid) {
        for (GhostShop gs : getGss()) {
            if (gs.getGoodsid() == goodsid) {
                gs.getLock().remove(myorderid);
                gs.getBuy().put(myorderid, DateTime.now());
            }
        }
        set();
    }

    //redis -----------------------------------------------

    /**
     * 获取redis key
     **/
    static private String key(String playerCode) {
        return String.format("PLAYER:%s:ACTIVE:%S", playerCode, acttype);
    }

    /**
     * 保存
     **/
    public void set() {
        try {
            setv(key(getPlayerCode()), this);
            check();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取ActiveModule_征战日志
     *
     * @param playerCode
     * @return
     */
    static public ActiveModule_神魔卡 get(String playerCode, Boolean isNewPlayer) {
        try {
            ActiveModule_神魔卡 module = getv(key(playerCode));

            //新用户不需要去查数据库
            if (module == null && !isNewPlayer) {
                module = MySQLCacheDAO.getV(key(playerCode), ActiveModule_神魔卡.class);
                if (module != null) {
                    module.set();
                }//同步到redis
            }

            if (module == null) {
                module = create(playerCode);
            }

            if (module == null) return null;

            module.update();
            module.check();
            return module;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 检查红点，活动是否开启
     **/
    public void check() {
        if (running()) {
            new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.开启);
        } else {
            new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.关闭);
        }

        if (running()) {
            checkGachaHero();        //抽将 检查红点
            checkGachaHeroTask();    //抽将任务 检查红点
            checkActive();            //活跃活动 检查红点
        } else {
            new TipHandle().updateTip(getPlayerCode(), TipType.活动_神魔卡_抽将, false);
            new TipHandle().updateTip(getPlayerCode(), TipType.活动_神魔卡_抽将任务, false);
            new TipHandle().updateTip(getPlayerCode(), TipType.活动_神魔卡_活跃任务, false);
        }
    }

    //活跃活动 检查红点
    private void checkActive() {
        GhostActive ga = getGa();

        //活跃任务
        for (GhostTask gt : ga.getActivemap().values()) {
            String taskcode = gt.getTaskcode();
            Task taskbean = Task.get(getPlayerCode(), taskcode);

            if (taskbean.isFinish() && !taskbean.isReward()) {
                new TipHandle().updateTip(getPlayerCode(), TipType.活动_神魔卡_活跃任务, true);
                return;
            }
        }

        //组合宝箱
        Map<String, actghosttaskreward> agtrmap = ActDataCenter.getAllData(actghosttaskreward.class, getPlayerCode());
        if (ga.getZhgetids().size() < agtrmap.size()) {
            for (actghosttaskreward data : agtrmap.values()) {
                if (ga.getZhgetids().contains(data.getId())) {
                    continue;
                }

                ArrayList<Integer> needpositions = new ArrayList<Integer>();
                for (int needposition : data.getPositionid()) {
                    needpositions.add(needposition);
                }

                if (needpositions.size() > 0 && ga.getFinishpositions().containsAll(needpositions)) {
                    new TipHandle().updateTip(getPlayerCode(), TipType.活动_神魔卡_活跃任务, true);
                    return;
                }
            }
        }

        //活跃任务完成数宝箱
        Map<String, actghosttasknumreward> agtnrmap = DataCenter.getAllData(actghosttasknumreward.class);
        if (ga.getFinishnumboxgetids().size() < agtnrmap.size()) {
            for (actghosttasknumreward data : agtnrmap.values()) {
                if (ga.getFinishnumboxgetids().contains(data.getId())) {
                    continue;
                }

                if (ga.getZhboxgetnum() >= data.getCondition()) {
                    new TipHandle().updateTip(getPlayerCode(), TipType.活动_神魔卡_活跃任务, true);
                    return;
                }
            }
        }

        new TipHandle().updateTip(getPlayerCode(), TipType.活动_神魔卡_活跃任务, false);
    }

    //抽将任务 检查红点
    private void checkGachaHeroTask() {
        for (GhostGachaTask gt : getGhostmap().values()) {
            String taskcode = gt.getTaskcode();
            Task taskbean = Task.get(getPlayerCode(), taskcode);

            if (taskbean != null && taskbean.isFinish() && !taskbean.isReward()) {
                new TipHandle().updateTip(getPlayerCode(), TipType.活动_神魔卡_抽将任务, true);
                return;
            }
        }
        new TipHandle().updateTip(getPlayerCode(), TipType.活动_神魔卡_抽将任务, false);
    }

    //抽将 检查红点
    private void checkGachaHero() {
        try {
            Currency item = Item.get(getPlayerCode(), CurrencyType.CT_物品, 1039);
            if (item.getNumber() > 0) {
                new TipHandle().updateTip(getPlayerCode(), TipType.活动_神魔卡_抽将, true);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        new TipHandle().updateTip(getPlayerCode(), TipType.活动_神魔卡_抽将, false);
    }

    //存储到数据库的方法
    public static void saveToDB(String playerCode) {
        try {
            String key = key(playerCode);
            if (touchBucket(key).isExists()) {
                ActiveModule_神魔卡 activeModule_神魔卡 = getv(key(playerCode));
                MySQLCacheDAO.setV(key, activeModule_神魔卡);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //从redis移走数据的操作
    public static void removeAllFromRedis(String playerCode) {
        try {
            touchBucket(key(playerCode)).delete();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }

    //lock --------------------------------------------------------
    @Override
    public String lockKey() {
        return String.format("lock:%s", key(getPlayerCode()));
    }

}
